

# -*- coding: UTF-8 -*-
import os, sys
CUR_PATH = os.path.dirname(os.path.abspath(__file__))
PKG_PATH = CUR_PATH[0:CUR_PATH.rindex('\\')]
sys.path.append(PKG_PATH)

from db_interface import db_interface
from public_func.exchange_date import cal_stock_exchange_date
from cal_func.ids_change_interval import get_max_exchange_date
from smart_chance.a_hold_stock_buy import stock_mkv_data
from scipy.stats import percentileofscore



def ids_contain_stock(industry_code="BK0475"):
    sql_ids = f"select stock from ids_stock_list where ids = '{industry_code}'"
    ids_data = list(db_interface.stock_base.select(sql_ids))
    stock_sh = [x[0] for x in ids_data if x[0].startswith("6")]
    stock_sz = [x[0] for x in ids_data if not x[0].startswith("6")]

    return stock_sh, stock_sz



def indus_stock_changpct(industry_code="BK0732"):
    start_date, end_date = cal_stock_exchange_date(30)
    start, end = get_max_exchange_date(start_date, end_date)
    print(start, end)
    stock_sh, stock_sz = ids_contain_stock(industry_code)
    sql_stock = f"select code, name, date, now from stock_days_sh where date between '{start}' and '{end}' and " \
             f"code in {tuple(stock_sh)} union " \
             f"select code, name, date, now from stock_days_sz where date between '{start}' and '{end}' and " \
             f"code in {tuple(stock_sz)} " \
             f"order by date desc"
    if len(stock_sz) == 1:
        sql_stock = f"select code, name, date, now from stock_days_sh where date between '{start}' and '{end}' and " \
                    f"code in {tuple(stock_sh)} union " \
                    f"select code, name, date, now from stock_days_sz where date between '{start}' and '{end}' and " \
                    f"code = '{stock_sz[0]}' " \
                    f"order by date desc"
    # print(sql_stock)
    stock_data = db_interface.stock_base.select(sql_stock)
    stock_dict = {}
    for item in stock_data:
        code, name, date, price = item
        date = date.strftime("%Y-%m-%d")
        if code not in stock_dict:
            stock_dict[code] = []
        stock_dict[code].append(
            (name, date, price)
        )
    result = []
    stock_mkv = stock_mkv_data(mkv=0)
    for stock, info in stock_dict.items():
        # print(stock, info)
        price_list = [x[2] for x in info]
        price = price_list[0]
        change_pct = price_list[0]/price_list[-1] - 1
        percent = percentileofscore(price_list, price, kind='rank')  ##
        # print(percent)
        mkv = stock_mkv[stock][1] if stock in stock_mkv else -1
        result.append({
            "name": info[0][0],
            "code": stock,
            "price": price,
            "change_pct": round(100*change_pct, 2),
            "mkv": mkv,
            "percent": round(percent, 2)
        })
    result = sorted(result, key=lambda x: x["change_pct"], reverse=True)

    return result






def ids_stock_change_plot(stock= "000001"):
    start_date, end_date = cal_stock_exchange_date(30)
    start, end = get_max_exchange_date(start_date, end_date)
    sql0 = f"select name, date, now from dongcai_ids_data where " \
            f"code = (select ids from ids_stock_list where stock = '{stock}' limit 1) and date " \
           f"between '{start}' and '{end}' order by date asc "
    query0 = db_interface.stock_base.select(sql0)
    ids_dict, ids_name = {}, ""
    for item in query0:
        name, date, price = item
        date = date.strftime("%Y-%m-%d")
        ids_dict[date] = price
        if not ids_name:
            ids_name = name

    table = "stock_days_sh" if stock.startswith("6") else "stock_days_sz"
    sql = f"SELECT name, date, now FROM {table} where code = '{stock}' and date " \
           f"between '{start}' and '{end}' order by date asc "
    query = db_interface.stock_base.select(sql)
    res = {
        "date": [],
        "name_list": [],
        "stock_price": [],
        "industry_price": []
    }
    stock_name = ""
    for item in query:
        name, date, price = item
        date = date.strftime("%Y-%m-%d")
        res['date'].append(date)
        res['stock_price'].append(price)
        industry_price = ids_dict.get(date, "")
        res['industry_price'].append(industry_price)
        if not stock_name:
            stock_name = name
    res['name_list'].append(stock_name)
    res['name_list'].append(ids_name)

    return res

